package sctu.edu.java.year2016.team01.chenhong.day20160604.chapter12_1;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by Administrator on 2016/6/4.
 * * 实现读取文件时出现一个表示进度的进度条，可使用ProgressMonitorInputStream。
 */
public class Student {


    public static void main(String args[]) throws Exception {
        //创建文件

        File file = new File("f:/student.txt");


        FileOutputStream out = new FileOutputStream(file);
        byte study[] = "学生姓名，学号，成绩.学生姓名，学号，成绩.学生姓名，学号，成绩.学生姓名，学号，成绩.学生姓名，学号，成绩.学生姓名，学号，成绩.学生姓名，学号，成绩.学生姓名，学号，成绩.".getBytes();
        out.write(study);
        out.close();




        JFrame jl = new JFrame("读取文件进度条");
        Container container = jl.getContentPane();
        container.setLayout(new FlowLayout());

        jl.setSize(300, 300);

        jl.setVisible(true);

        jl.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);


        ProgressMonitorInputStream monitor;

        monitor = new ProgressMonitorInputStream(jl, "读取数据", new FileInputStream(file));
        ProgressMonitor progressMonitor = monitor.getProgressMonitor();


        int read_unit = 2;                   // 设置每次读取的字节数
        int all = monitor.available();       // 得到目标文件的总字节数
        int readed = 0;                      // 每次实际读取到的字节数
        byte[] data = new byte[read_unit];   // 字节数组，保存读取到的字节数


        while (monitor.available() > 0) {
            Thread.sleep(100);                 // 故意放慢速度好看清进度条
            int in = monitor.read(data);

            readed += in;
            // System.out.write(data);
            float process = (float) readed / all * 100;// 算出百分比

            progressMonitor.setNote("archived " + process + " %");// 显示在进度条上

        }
    }
}
